package com.cherrypt.api.tracker.controller;

import com.cherrypt.api.tracker.enums.TrackerResponseEnum;
import com.cherrypt.api.tracker.model.dataobject.Peer;
import com.cherrypt.api.tracker.model.dataobject.Torrent;
import com.cherrypt.api.tracker.model.dataobject.User;
import com.cherrypt.api.tracker.util.TrackerResponseUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * @author intent
 * @date 2019/7/24 10:56
 * @about <link href='http://zzyitj.xyz/'/>
 */
@RestController
@RequestMapping(value = "${api.url.tracker.value}")
public class AnnounceController extends AnnounceImpl {
    private static final Logger logger = LoggerFactory.getLogger(AnnounceController.class);

    private HashMap<String, User> userMap = new HashMap<>();
    private HashMap<byte[], Torrent> torrentMap = new HashMap<>();
    private HashMap<Integer, List<Peer>> peerMap = new HashMap<>();

    @Override
    Torrent getTorrentByHash(byte[] hash) {
        return torrentMap.get(hash);
    }

    @Override
    User getUserByPasskey(String passkey) {
        return userMap.get(passkey);
    }

    @Override
    List<Peer> getAllPeers(Integer tid) {
        return peerMap.get(tid);
    }

    /**
     * 如果left为0则说明辅种
     * 否则，如果peers为null返回错误
     *
     * @param peer
     * @param peers
     * @param torrent
     */
    @Override
    String start(Peer peer, List<Peer> peers, Torrent torrent) {
        if (peer.getLeft() == 0) {
            if (peers == null) {
                peers = new ArrayList<>();
                peers.add(peer);
            }
            peerMap.put(torrent.getId(), peers);
            return TrackerResponseUtils.success(peers);
        } else {
            if (peers == null || peers.size() == 0) {
                return TrackerResponseUtils.error(TrackerResponseEnum.NO_PEER);
            } else {
                return TrackerResponseUtils.success(peers);
            }
        }
    }

    @Override
    String complete(Peer peer, List<Peer> peers, Torrent torrent) {
        return null;
    }

    @Override
    String stop(Peer peer, List<Peer> peers, Torrent torrent) {
        return null;
    }

    @Override
    String pause(Peer peer, List<Peer> peers, Torrent torrent) {
        return null;
    }

    @Override
    String work(Peer peer, List<Peer> peers, Torrent torrent) {
        return null;
    }

    @GetMapping(value = "${api.url.tracker.scrape}")
    public String scrape(HttpServletRequest request) {
        return retScrape(request);
    }


    @GetMapping(value = "${api.url.tracker.announce}")
    public String announce(HttpServletRequest request) {
        return retAnnounce(request);
    }
}
